package com.example.hj.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by HuangJian on 2020/7/22.
 */
@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/test")
    public String test() {
        String result=restTemplate.getForEntity("http://eureka-client/tt", String.class).getBody();
        System.out.println("------:"+result);
        return result;
    }

    /**
     * 调用 微服务
     * 在需要有熔断机制的方法上添加 @HystrixCommand，属性fallbackMethod是熔断时返回的方法
     */
    @HystrixCommand(fallbackMethod = "getDefaultUser")
    @GetMapping("/getUser")
    public String getUser(Integer id) {
        String url = "http://eureka-client/user/" + id;
        return restTemplate.getForObject(url, String.class);
    }

    public String getDefaultUser(Integer id) {
        System.out.println("熔断，默认回调函数");
        return "{\"id\":-1,\"name\":\"熔断用户\",\"password\":\"123456\"}";
    }
}

